import {queryStr, cleanObject} from 'utils'
import * as auth from 'auth-provider'
import { useAuth } from 'context/auth-context';
import { useCallback } from 'react';

const apiUrl = process.env.REACT_APP_API_URL;
//RequestInit里面没有data和token，需要手动添加
interface Config extends RequestInit {
    token?:string,
    data?:object
}
export const http = async (
    endpoint: string, 
    {data = {}, token, headers, ...customConfig}: Config = {}
    ) => {
    const config = {
        method: 'GET',
        headers: {
            Authorization: token ? `Bearer ${token}` : '',
            'Content-type': data ? 'application/json' : '',
        },
        ...customConfig
    }
    if (config.method.toUpperCase() === 'GET') {
        endpoint+=`?${queryStr(data)}`
        //console.log('请求参数url===', endpoint)
    } else {
        config.body = JSON.stringify(data)
    }
    return window.fetch(`${apiUrl}/${endpoint}`, config).then(async response => {
      if (response.status === 401) {  //token失效
        await auth.logout()
        window.location.reload()
        return Promise.reject({message: '请重新登录'})
      }
      const data = await response.json()
      if(response.ok) {
        return data
      } else {
        return Promise.reject(data) //服务端返回的请求有问题时，不会抛出异常
        //axios和fetch不一样，axios可以在状态不为2**的时候抛出异常
      }
    })
}

export const useHttp = () => {
    const {user} = useAuth()
    return useCallback((...[endpoint, config]: Parameters<typeof http>) => 
    http(endpoint, {...config, token: user?.token,}), [user?.token])
}